package org.oa.ai.word;

import org.apache.poi.hwpf.HWPFDocument;
import org.apache.poi.hwpf.converter.PicturesManager;
import org.apache.poi.hwpf.converter.WordToHtmlConverter;
import org.apache.poi.xwpf.usermodel.*;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Element;
import org.w3c.dom.Document;

import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import java.io.*;

public class WordToHtmlUtil {

    /**
     * 将 .docx 或 .doc 文件转换为 HTML 字符串
     *
     * @param inputStream Word 文件输入流
     * @param isDoc       是否是 .doc 格式
     * @return HTML 字符串
     */
    public static String convertWordToHtml(InputStream inputStream, boolean isDoc) throws Exception {
        if (isDoc) {
            // 处理 .doc 文件
            try (HWPFDocument wordDocument = new HWPFDocument(inputStream)) {
                WordToHtmlConverter wordToHtmlConverter = new WordToHtmlConverter(
                        DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument());
                wordToHtmlConverter.setPicturesManager((content, pictureType, suggestedName, widthInches, heightInches) -> suggestedName);
                wordToHtmlConverter.processDocument(wordDocument);

                Document htmlDocument = wordToHtmlConverter.getDocument();
                DOMSource domSource = new DOMSource(htmlDocument);
                StreamResult streamResult = new StreamResult(new StringWriter());

                Transformer transformer = TransformerFactory.newInstance().newTransformer();
                transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
                transformer.setOutputProperty(OutputKeys.METHOD, "html");
                transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
                transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");
                transformer.setOutputProperty(OutputKeys.INDENT, "yes");

                transformer.transform(domSource, streamResult);
                return streamResult.getWriter().toString();
            }
        } else {
            // 处理 .docx 文件
            return convertDocxToHtml(inputStream);
        }
    }

    /**
     * 将 .docx 文件转换为 HTML 字符串
     */
    private static String convertDocxToHtml(InputStream inputStream) throws Exception {
        // 确保流可读且不为空
        if (inputStream == null || inputStream.available() == 0) {
            throw new IllegalArgumentException("输入流为空或不可读");
        }
        XWPFDocument document = new XWPFDocument(inputStream);
        org.jsoup.nodes.Document htmlDoc = Jsoup.parse("<html><head><meta charset='UTF-8'/><body></body></html>");
        Element body = htmlDoc.body();

        // 遍历所有段落
        for (XWPFParagraph paragraph : document.getParagraphs()) {
            Element pElement = body.appendElement("p");
            for (XWPFRun run : paragraph.getRuns()) {
                String text = run.getText(0);
                if (text != null && !text.isEmpty()) {
                    pElement.appendText(text);
                }
                if (run.isBold()) {
                    pElement.append("<b>" + text + "</b>");
                }
                if (run.isItalic()) {
                    pElement.append("<i>" + text + "</i>");
                }
                // 可继续添加其他样式处理（颜色、字体大小等）
            }
        }

        // 遍历所有表格
        for (XWPFTable table : document.getTables()) {
            Element tableElement = body.appendElement("table").attr("border", "1");
            for (XWPFTableRow row : table.getRows()) {
                Element trElement = tableElement.appendElement("tr");
                for (XWPFTableCell cell : row.getTableCells()) {
                    Element tdElement = trElement.appendElement("td");
                    for (XWPFParagraph paragraph : cell.getParagraphs()) {
                        tdElement.append(paragraph.getText());
                    }
                }
            }
        }

        return htmlDoc.html();
    }

//    public static void main(String[] args) {
//        try (InputStream inputStream = new FileInputStream("path/to/your/document.doc")) {
//            String html = convertWordToHtml(inputStream, true); // 如果是 .doc 文件，则传入 true
//            System.out.println(html);
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//    }
}
